/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servidor;

import java.util.Iterator;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.swing.DefaultListModel;



/**
 *
 * @author daniel
 */
public class pofin extends javax.swing.JFrame {

    
    private EntityManagerFactory emf;
    private EntityManager em;
    private Nodo iteration;
    private Proceso iteratorProceso;
    private Directorio iteratorDirectorio;
    /**
     * Creates new form pofin
     */
    public pofin() {
        initComponents();
        initMyComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jComboBox1 = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListProcesos = new javax.swing.JList();
        jScrollPane3 = new javax.swing.JScrollPane();
        jListDirectorios = new javax.swing.JList();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Nodos");

        jListProcesos.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(jListProcesos);

        jTabbedPane1.addTab("Procesos", jScrollPane2);

        jListDirectorios.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane3.setViewportView(jListDirectorios);

        jTabbedPane1.addTab("Directorios", jScrollPane3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 373, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(99, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(36, 36, 36)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
        
        if (evt.getStateChange()==1){
        //Creamos una Query con una consulta ya definida ""Ciudad.findByPId"
          this.listarProcesos();
          this.listarDirectorios();
     } // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ItemStateChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(pofin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(pofin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(pofin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(pofin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new pofin().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jListDirectorios;
    private javax.swing.JList jListProcesos;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane jTabbedPane1;
    // End of variables declaration//GEN-END:variables

    
public void loadComboBox() {
    //Creamos una Query
    //"Pais.findAll" es una query que fue definida automaticamente gracias al mapeo de la db
    //Luego obtenemos los resultados y los recorremos
    Iterator it = em.createNamedQuery("Nodo.findAll").getResultList().iterator();
    while(it.hasNext()) {
        //Agrego el resultado al Combobox
        iteration = ((Nodo)it.next());
        //System.out.println(""+ iteration.getIDNodo() +"");
        this.jComboBox1.addItem(iteration);
        
    }

}


private void listarProcesos(){
 Query query = em.createNamedQuery("Proceso.findByIDNodo");
        
        //Esa query requiere pasarle un valor "pId" , la id del Pais
        query.setParameter("IDNodo", (((Nodo)this.jComboBox1.getSelectedItem())));
        
        //Elimino todos los elementos agregados al Modelo del JList
        ((DefaultListModel)jListProcesos.getModel()).removeAllElements();
        //Recorro los resultados de la Query
        Iterator it = query.getResultList().listIterator();
        while(it.hasNext()) {
            iteratorProceso= ((Proceso)it.next());
            // System.out.println(""+ iteratorProceso.getIDProceso() +"");
            //Agrego el resultado a la JList
            ((DefaultListModel)jListProcesos.getModel()).addElement(iteratorProceso.getProcesoPID());
       
        }
   }

private void listarDirectorios(){
        Query query = em.createNamedQuery("Directorio.findByIDNodo");
        
        //Esa query requiere pasarle un valor "pId" , la id del Pais
        query.setParameter("IDNodo", (((Nodo)this.jComboBox1.getSelectedItem())));
        
        //Elimino todos los elementos agregados al Modelo del JList
        ((DefaultListModel)jListDirectorios.getModel()).removeAllElements();
        //Recorro los resultados de la Query
        Iterator it = query.getResultList().listIterator();
        while(it.hasNext()) {
            iteratorDirectorio= ((Directorio)it.next());
            // System.out.println(""+ iteratorProceso.getIDProceso() +"");
            //Agrego el resultado a la JList
            ((DefaultListModel)jListDirectorios.getModel()).addElement(iteratorDirectorio.getDirectorioDir());
       
        }
   }


    private void initMyComponents() {
        
    //inicializamos el EntityManagerFactory
    emf = Persistence.createEntityManagerFactory("ProyectoDistribuidosPU");
    //inicializamos entity manager
    em = emf.createEntityManager();
    //Agregamos un Model al JList
    jListProcesos.setModel(new DefaultListModel());
    jListDirectorios.setModel(new DefaultListModel());
    //Posicionamos la ventana en el centro
    this.setLocationRelativeTo(null);
    //Llamamos al metodo que TestPUllena el combobox con paises
    loadComboBox();
    }

}
